import React from 'react';
import Navbar from './Navbar';
import Homepage from './Homepage';
import { getRouteParams, getSearchParams, changeTitle } from '../../util';
import * as API_NAVBAR from '../../apis/navbar';

class Portal extends React.Component {
  constructor(props) {
    super(props);
    this.setNavbarHeight = this.setNavbarHeight.bind(this);

    const params = getSearchParams(props.location.search);
    this.state = {
      isSetting: params.isSetting == 'true',
      hasNavbar: false,
      navbarHeight: 0
    };
  }

  componentWillMount() {
    const params = getRouteParams(this.props);
    const { hpid } = params;

    API_NAVBAR.getHasNavbar({ id: hpid }).then(result => {
      const { data = {} } = result;
      const { isshownavbar = 1 } = data;
      const hasNavbar = isshownavbar != 0;
      this.setState({ hasNavbar });

      if (!hasNavbar) {
        API_NAVBAR.getNavbarMenus().then(result => {
          const { menus = [] } = result;
          this.getSelectedMenu(menus, hpid);
        });
      }
    });
  }

  render() {
    const { isSetting, hasNavbar, navbarHeight } = this.state;

    return (
      <React.Fragment>
        {!isSetting && hasNavbar ? <Navbar navbarHeight={navbarHeight} setNavbarHeight={this.setNavbarHeight} /> : null}
        <Homepage isSetting={isSetting} navbarHeight={navbarHeight} />
      </React.Fragment>
    );
  }

  getSelectedMenu(menus, selected) {
    for (let i = 0, len = menus.length; i < len; i++) {
      const item = menus[i];
      if (item.menuid == selected) {
        changeTitle(item.infoname);
        break;
      } else if (item.child && item.child.length) {
        this.getSelectedMenu(item.child, selected);
      }
    }
  }

  setNavbarHeight(height) {
    this.setState({ navbarHeight: height });
  }
}

export default Portal;
